<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>申请提交</el-breadcrumb-item>
      <el-breadcrumb-item>入库申请</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 步骤条 -->
    <el-steps :active="active" align-center>
      <el-step title="填写申请信息"></el-step>
      <el-step title="审核中"></el-step>
      <el-step title="等待验收"></el-step>
      <el-step title="验收完成"></el-step>
    </el-steps>
    <div class="form-container">
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        label-width="80px"
        width="50%"
      >
        <el-form-item label="审核人" prop="reviewer">
          <el-select
            v-bind:disabled="isreadonly"
            size="small"
            clearable
            v-model="ruleForm.reviewer"
            placeholder="请选择"
          >
            <el-option
              v-for="item in this.checkandreview"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="验收人" prop="checker">
          <el-select
            v-bind:disabled="isreadonly"
            size="small"
            clearable
            v-model="ruleForm.checker"
            placeholder="请选择"
          >
            <el-option
              v-for="item in this.checkandreview"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="材料清单">
          <el-tag
            :key="tag"
            v-for="tag in dynamicTags"
            closable
            :disable-transitions="false"
            @close="handleClose(tag)"
          >
            {{ tag }}
          </el-tag>
          <el-button
            class="button-new-tag"
            v-show="!isreadonly"
            size="small"
            @click="handleEdit()"
          >
            + 添加新的材料单</el-button
          >
        </el-form-item>
        <el-form-item label="入库时间" prop="applyDate" style="width: 100%">
          <el-col :span="11">
            <el-date-picker
              v-bind:disabled="isreadonly"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="申请入库时间"
              v-model="ruleForm.applyDate"
            ></el-date-picker>
          </el-col>
        </el-form-item>

        <el-form-item label="申请备注" prop="desc">
          <el-input
            type="textarea"
            v-bind:disabled="isreadonly"
            v-model="ruleForm.desc"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-show="!isreadonly" @click="onSubmit('ruleForm')"
            >提交入库申请</el-button
          >
          <span v-show="isreadonly">等待审核</span>
        </el-form-item>
      </el-form>
    </div>
    <!-- 编辑界面 -->
    <el-dialog
      :title="title"
      :visible.sync="editFormVisible"
      width="30%"
      @click="closeDialog('edit')"
    >
      <el-form
        label-width="80px"
        ref="editForm"
        :model="editForm"
        :rules="rulesss"
      >
        <el-form-item label="入库材料" prop="materials">
          <el-select
            @change="materialsChange"
            v-model="editForm.materials"
            placeholder="请选择"
          >
            <el-option-group
              v-for="group in options"
              :key="group.label"
              :label="group.label"
            >
              <el-option
                v-for="item in group.options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-option-group>
          </el-select>
          <span v-show="isShowP">指导价:{{ this.thisprice }}</span>
        </el-form-item>
        <el-form-item label="入库数量" prop="quantity">
          <el-input
            type="number"
            oninput="value=value.replace(/^(0+)|[^\d]+/g,'')"
            @blur="handleIdCardChange"
            v-model="editForm.quantity"
            placeholder="数量"
          ></el-input>
          <span v-show="isShowP">单位:{{ this.thisunit }}</span>
        </el-form-item>
        <el-form-item label="入库金额">
          <el-input
            type="number"
            readonly
            v-model="sumprice"
            placeholder="价格"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog('edit')">取消</el-button>
        <el-button
          size="small"
          type="primary"
          :loading="loading"
          class="title"
          @click="submitForm('editForm')"
          >保存</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 导入请求方法
import { commitApply, getMaterialPrice } from "../../api/applyMG";
import { getUsersByStoreid, getMaterialItemByStoreid } from "../../api/basisMG";
import { getCookie } from "../../utils/util";
export default {
  data() {
    return {
      loading: false, //是显示加载
      editFormVisible: false, //控制编辑页面显示与隐藏
      title: "添加材料",
      active: 1,
      isreadonly: false,
      // 材料清单
      number: 0,
      // 单个材料对象
      material: {
        id: 0,
        quantity: 0,
        price: 0,
      },
      thisprice: 0,
      thisunit: "",
      sumprice: 0,
      isShowP: false,
      // 材料清单组
      materiallist: [],
      // tag组
      dynamicTags: [],
      // 申请单主体
      ruleForm: {
        checker: 0,
        reviewer: 0,
        desc: "",
      },
      // 申请单材料清单添加
      editForm: {
        price: "",
        quantity: "",
        materials: "",
      },
      // 材料选择框数据源
      options: [
        {
          label: "热门城市",
          options: [
            {
              value: "1",
              label: "上海",
            },
            {
              value: "2",
              label: "北京",
            },
          ],
        },
        {
          label: "城市名",
          options: [
            {
              value: "3",
              label: "成都",
            },
            {
              value: "4",
              label: "深圳",
            },
          ],
        },
      ],
      // 审核人和验收人选择框数据源
      checkandreview: [],
      // cookie中的基本用户信息对象
      user: {
        id: 0,
        role: "",
        store: "",
        storeid: 0,
        userName: "",
        useremail: "",
      },
      // 申请单主体验证
      rules: {
        reviewer: [
          { required: true, message: "请选择审核人", trigger: "blur" },
        ],
        checker: [{ required: true, message: "请选择验收人", trigger: "blur" }],
        applyDate: [
          { required: true, message: "请选择入库时间", trigger: "blur" },
        ],
      },
      // 材料清单验证
      rulesss: {
        materials: [
          { required: true, message: "请选择入库材料", trigger: "blur" },
        ],
        quantity: [
          { required: true, message: "请填写入库数量", trigger: "blur" },
        ],
      },
    };
  },
  /**
   * 创建完毕
   */
  created() {
    this.number = 0;
    this.user = JSON.parse(getCookie("userdata"));
    console.log(this.user);
    //this.clearlist();
    this.getSelectItem();
  },
  /**
   * 里面的方法只有被调用才会执行
   */
  methods: {
    // 获取此仓库的仓库负责人数据(作为审核人和验收人选择)
    getSelectItem() {
      getUsersByStoreid({ storeid: this.user.storeid }).then((res) => {
        if (res.status == 200) {
          this.checkandreview = res.data;
        } else {
          this.$message({
            type: "info",
            message: "获取审核人列表失败,刷新页面试试",
          });
        }
      });
      // 获取此仓库的材料种类列表数据
      getMaterialItemByStoreid({ storeid: this.user.storeid }).then((res) => {
        if (res.status == 200) {
          this.options = res.data;
          console.log(res.data);
          console.log(this.options);
        } else {
          this.$message({
            type: "info",
            message: "获取材料种类列表失败,刷新页面试试",
          });
        }
      });
    },
    // 提交申请
    onSubmit(editData) {
      this.$refs[editData].validate((valid) => {
        if (valid) {
          // 检查材料组是否有数据，检查tag组是否有数据
          if (Array.isArray(this.dynamicTags) && this.dynamicTags.length > 0) {
            // dynamicTags包含数据
            // 提交用户id 提交申请单对象 提交材料组 提交tag组
            commitApply({
              userid: this.user.id,
              storeid: this.user.storeid,
              type:"入库",
              tags: this.dynamicTags,
              apply: this.ruleForm,
              materials: this.materiallist,
            })
              .then((res) => {
                this.editFormVisible = false;
                this.loading = false;
                if (res.status == 201) {
                  this.$message({
                    type: "success",
                    message: "入库申请提交成功！请耐心等待管理员审核验收",
                  });
                  // 步骤条到第二步且form表单变为不可修改
                  this.active = 2;
                  this.isreadonly =true;
                } else {
                  this.$message({
                    type: "info",
                    message: res.msg,
                  });
                }
              })
              .catch((err) => {
                this.editFormVisible = false;
                this.loading = false;
                this.$message.error("提交失败，请稍后再试！");
              });
          } else {
            this.$message.error("请最少添加一项入库材料");
          }
        }
      });
    },
    // 删除tag
    handleClose(tag) {
      if (this.isreadonly) {
        return false;
      } else {
        this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
      }
    },
    //显示添加界面
    handleEdit: function () {
      // 打开添加隐藏框
      this.editFormVisible = true;
    },
    // 选择材料框发生变化后
    materialsChange() {
      this.isShowP = true;
      // 发送请求获取指导价和单位
      getMaterialPrice({ id: this.editForm.materials }).then((res) => {
        if (res.status == 200) {
          this.thisprice = res.data.price;
          this.thisunit = res.data.unit;
        } else {
          this.$message({
            type: "info",
            message: "获取材料单位和指导价失败,刷新页面试试",
          });
        }
      });
      this.sumprice = this.editForm.quantity * this.thisprice;
    },
    // 填写数量计算总金额
    handleIdCardChange() {
      this.sumprice = this.editForm.quantity * this.thisprice;
    },
    // 编辑保存提交方法
    submitForm(editData) {
      this.$refs[editData].validate((valid) => {
        if (valid) {
          // 添加材料清单到组内，添加tag组
          this.dynamicTags.push(
            this.number +
              ".数量:" +
              this.editForm.quantity +
              ",金额:" +
              this.sumprice
          );
          let acse =
            this.number +
            "." +
            this.editForm.materials +
            "!" +
            this.editForm.quantity ;
          this.materiallist.push(acse);
          // 添加完成后 材料对象置空 序号加1
          this.number = this.number + 1;
          // 关闭显示
          this.editFormVisible = false;
          // log
          console.log("-------------------");
          console.log(this.dynamicTags);
          console.log("-------------------");
          console.log(this.materiallist);
        }
      });
    },
    // 关闭编辑、增加弹出框
    closeDialog(dialog) {
      if (dialog == "edit") {
        this.editFormVisible = false;
      }
    },
    // 清空材料清单组和tag组
    clearlist() {
      for (const key in this.dynamicTags) {
        this.dynamicTags[key] = "";
      }
      for (const key in this.materiallist) {
        this.materiallist[key] = "";
      }
    },
  },
};
</script>

<style scoped>
.form-container {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 80%;
}
</style>


